// resume.js

document.addEventListener('DOMContentLoaded', function () {
    // 获取表单和展示区
    const resumeForm = document.querySelector('#personal-info form');
    const resumeDisplay = document.getElementById('resume-display');
    const myResumeTab = document.getElementById('my-resume');
    let currentResumeId = null;

    // 获取我的简历并填充表单和展示区
    async function fetchAndShowResume() {
        try {
            const res = await fetch('http://localhost:3001/api/resumes/my-resume', { method: 'GET' });
            const data = await res.json();
            if (data.success && data.data) {
                const resume = data.data;
                currentResumeId = resume.id;
                // 填充表单
                if (resumeForm) {
                    for (const key in resume) {
                        const input = resumeForm.querySelector(`[name="${key}"]`);
                        if (input) input.value = resume[key];
                    }
                }
                // 填充展示区
                if (resumeDisplay) {
                    resumeDisplay.innerHTML = renderResumeDisplay(resume);
                    addDeleteBtnListener();
                }
            } else {
                if (resumeDisplay) resumeDisplay.innerHTML = '<p>暂无简历，请先填写并保存个人信息。</p>';
                currentResumeId = null;
            }
        } catch (err) {
            if (resumeDisplay) resumeDisplay.innerHTML = '<p style="color:red;">获取简历失败</p>';
        }
    }

    // 渲染简历内容
    function renderResumeDisplay(resume) {
        return `
            <div><strong>姓名：</strong>${resume.name || ''}</div>
            <div><strong>性别：</strong>${resume.gender || ''}</div>
            <div><strong>出生日期：</strong>${resume.birthdate || ''}</div>
            <div><strong>手机号：</strong>${resume.phone || ''}</div>
            <div><strong>邮箱：</strong>${resume.email || ''}</div>
            <div><strong>最高学历：</strong>${resume.education || ''}</div>
            <div><strong>专业：</strong>${resume.major || ''}</div>
            <div><strong>毕业院校：</strong>${resume.school || ''}</div>
            <div><strong>毕业时间：</strong>${resume['graduation-date'] || ''}</div>
            <div><strong>工作经验：</strong>${resume['work-experience'] || ''}</div>
            <div><strong>简历标题：</strong>${resume['resume-title'] || ''}</div>
            <div><strong>个人简介：</strong>${resume['resume-content'] || ''}</div>
            <div><strong>专业技能：</strong>${resume.skills || ''}</div>
            <button id="delete-resume-btn" style="margin-top:10px;color:#fff;background:#e74c3c;border:none;padding:8px 16px;border-radius:4px;cursor:pointer;">删除简历</button>
        `;
    }

    // 实时保存逻辑
const debounce = (fn, delay) => {
    let timer;
    return (...args) => {
        clearTimeout(timer);
        timer = setTimeout(() => fn(...args), delay);
    };
};

async function saveResume() {
    const formData = new FormData(resumeForm);
    const data = {};
    for (const [key, value] of formData.entries()) {
        data[key] = value;
    }
    
    try {
        const method = currentResumeId ? 'PUT' : 'POST';
        const url = currentResumeId ? `/api/resumes/${currentResumeId}` : '/api/resumes';
        
        const res = await fetch(url, {
            method,
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(data)
        });
        
        const result = await res.json();
        if (result.success) {
            console.log('自动保存成功');
            currentResumeId = result.data?.id || currentResumeId;
            fetchAndShowResume();
        }
    } catch (err) {
        console.error('自动保存失败');
    }
}

// 表单实时保存
if (resumeForm) {
    // 保留原有提交事件
    resumeForm.addEventListener('submit', async function (e) {
        e.preventDefault();
        await saveResume();
        alert('手动保存成功！');
    });
    
    // 添加输入监听
    const inputs = resumeForm.querySelectorAll('input, textarea, select');
    const debouncedSave = debounce(saveResume, 300);
    
    inputs.forEach(input => {
        input.addEventListener('input', debouncedSave);
    });
}
            e.preventDefault();
            // 表单验证
            const requiredFields = ['name', 'phone', 'email', 'education', 'school', 'major'];
            let isValid = true;
            
            requiredFields.forEach(field => {
                const input = resumeForm.querySelector(`[name="${field}"]`);
                if (input && !input.value.trim()) {
                    isValid = false;
                    input.classList.add('error');
                    setTimeout(() => input.classList.remove('error'), 3000);
                }
            });
            
            // 邮箱格式验证
            const emailInput = resumeForm.querySelector('[name="email"]');
            if (emailInput && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(emailInput.value)) {
                isValid = false;
                emailInput.classList.add('error');
                setTimeout(() => emailInput.classList.remove('error'), 3000);
                alert('请输入有效的邮箱地址');
            }
            
            if (!isValid) return;
            
            e.preventDefault();
            const formData = new FormData(resumeForm);
            const data = {};
            for (const [key, value] of formData.entries()) {
                data[key] = value;
            }
            try {
                const res = await fetch('http://localhost:3001/api/resumes', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify(data)
                });
                const result = await res.json();
                if (result.success) {
                    alert('简历保存成功！');
                    fetchAndShowResume();
                } else {
                    alert('保存失败：' + (result.message || '未知错误'));
                }
            } catch (err) {
                alert('保存失败，请稍后重试');
            }
        });
    }
        if (btn && currentResumeId) {
            btn.onclick = async function () {
                if (!confirm('确定要删除简历吗？')) return;
                try {
                    const res = await fetch(`http://localhost:3001/api/resumes/${currentResumeId}`, { method: 'DELETE' });
                    const result = await res.json();
                    if (result.success) {
                        alert('简历已删除');
                        fetchAndShowResume();
                    } else {
                        alert('删除失败：' + (result.message || '未知错误'));
                    }
                } catch (err) {
                    alert('删除失败，请稍后重试');
                }
            };
        }
    }

    // tab切换时刷新简历内容
    if (myResumeTab) {
        myResumeTab.addEventListener('click', fetchAndShowResume);
    }
    // 页面加载时自动获取简历
    fetchAndShowResume();
});